<!-- <script type="text/javascript"> -->
{% load i18n %}
    /**
     * @param {boolean} html_exists True if the html has already been converted.
     * @param {number} page_num The number of pages of this document
     * @param {string|undefined} outline The outline content of the converted html.
     *      If html_exists is true, then it is undefined since the outline is already rendered in the HTML.
     */
    function load_document(html_exists, page_num, outline) {
        $('#convert-loading').remove();
        var base_page_url = "{% url 'office_convert_static' obj_id %}/",
            page_urls = [];

        for (var i = 1; i < page_num + 1; i++) {
            page_urls.push(base_page_url + i + '.page');
        }

        if (!html_exists) {
            $('#outline').html(outline);
        }

        var has_outline;
        if (html_exists) {
            outline_html = $.trim($('#outline').html());
            has_outline = outline_html;
        } else {
            has_outline = $.trim(outline);
        }
        
        $('#converted-html').append('<div id="pdf2html-toolbar-1"></div>');
        if (has_outline) {
            var sidebar = $('#sidebar'),
                page_container = $('#page-container'),
                hide_outline, show_outline;

            $('#outline .l').removeAttr('data-dest-detail'); // make the anchor links work
            sidebar.removeClass('hide');

            var toolbar = $('#pdf2html-toolbar-1');
            toolbar.append('<span class="icon-caret-left" title="{% trans "hide outline" %}" id="hide-outline"></span>');
            toolbar.append('<span class="icon-caret-right hide" title="{% trans "show outline" %}" id="show-outline"></span>');

            hide_outline = $('#hide-outline');
            show_outline = $('#show-outline');

            toolbar.css({'left':250, 'bottom': ($(window).height() + $(window).scrollTop() - $('#file-view').offset().top)/2 - toolbar.height()/2});
            toolbar.click(function() {
                if (show_outline.hasClass('hide')) {
                    sidebar.addClass('hide').removeClass('opened');
                    hide_outline.addClass('hide');
                    show_outline.removeClass('hide');
                    toolbar.css({'left':0});
                } else {
                    sidebar.removeClass('hide').addClass('opened');
                    show_outline.addClass('hide');
                    hide_outline.removeClass('hide');
                    toolbar.css({'left':250});
                }
            });
        }

        new pdf2htmlEX.Viewer({
            container_id : 'page-container',
            sidebar_id : 'sidebar',
            outline_id : 'outline',
            page_urls : page_urls
        });

        // zoom in, zoom out
        var scale_ratio = 1,
            scale_ratio_offset = 0.1;
        var scale = function(ele, ratio) {
            ele.css({
                'transform':'scale(' + ratio + ')',
                '-webkit-transform':'scale(' + ratio + ')',
                '-ms-transform':'scale(' + ratio + ')',
                'transform-origin':'center 0%',
                '-webkit-transform-origin':'center 0%',
                '-ms-transform-origin':'center 0%'
            });
        };

        $('#converted-html').append('<div id="pdf2html-toolbar-2" class="pdf2html-toolbar"></div>');
        $('#pdf2html-toolbar-2').append('<span class="icon-zoom-out" id="zoom-out"></span><span class="icon-zoom-in" id="zoom-in"></span>').css({'left': $(window).width()/2 - $('#pdf2html-toolbar-2').outerWidth(true)/2});

        var file_cont = $('#file-view'), //file container
            orig_pg_total_h; 
        $('#zoom-in, #zoom-out').click(function() {
            // get orig data before zoom in/out
            var op = $(this).attr('id'),
                pg_num = $('.pd').length,
                orig_win_scrollTop = $(window).scrollTop(),
                orig_pg_h, cur_pg, pg_h_offset;
            
            if (!orig_pg_total_h && scale_ratio == 1) {
                orig_pg_total_h = file_cont.height();
            }

            orig_pg_h = orig_pg_total_h*scale_ratio/pg_num;
            cur_pg = (orig_win_scrollTop - $('#page-container').offset().top)/orig_pg_h;

            // zoom in/out
            if (op == 'zoom-in') {
                scale_ratio += scale_ratio_offset;
            } else {
                scale_ratio -= scale_ratio_offset;
            }
            if (scale_ratio <= 0) {
                return ;
            }
            scale($('#page-container'), scale_ratio);
            
            // modify file container's height
            file_cont.height(orig_pg_total_h*scale_ratio); 

            // scroll to the right cur page 
            pg_h_offset = (orig_pg_total_h * scale_ratio_offset)/pg_num;
            if (op == 'zoom-in') {
                $(window).scrollTop(orig_win_scrollTop + cur_pg*pg_h_offset);
            } else {
                $(window).scrollTop(orig_win_scrollTop - cur_pg*pg_h_offset);
            }
        });
    }

    // handle outline(fixed or not) when scroll
    $(window).scroll(function() {
        var outline = $('#outline');
        if (!$.trim(outline.html())) {
            return;
        }
        var toolbar1 = $('#pdf2html-toolbar-1');
        if ($(window).scrollTop() > $('#page-container').offset().top) {
            outline.addClass('fixed-outline').css({'height':$(window).height() - parseInt(outline.css('padding-top')) - parseInt(outline.css('padding-bottom'))});
            toolbar1.css({'bottom':'50%'});
        } else {
            outline.removeClass('fixed-outline').removeAttr('style');
            toolbar1.css({'bottom':($(window).height() + $(window).scrollTop() - $('#file-view').offset().top)/2 - toolbar1.height()/2});
        }
    });

    {% if html_exists %}
    load_document(true, {{ html_detail.page_num }});
    {% else %}

    var m_page_num;
    function get_outline() {
        $.ajax({
            url: "{% url 'office_convert_static' obj_id %}/file.outline",
            dataType: 'text'
        }).done(function(outline) {
            load_document(false, m_page_num, outline);
        });
    }

    function get_file_css() {
        var css_href = "{% url 'office_convert_static' obj_id %}/file.css";
        $('head').append('<link rel="stylesheet" type="text/css" href="' + css_href + '" />');
    }

    function query_page_num() {
        $.ajax({
            url: "{% url 'office_convert_query_page_num' %}?file_id={{ obj_id }}",
            cache: false,
            dataType: 'json',
            success: function(data) {
                if (data['success']) {
                    m_page_num = data['count'];
                    get_file_css();
                    get_outline();
                } else {
                    str = "{% trans "Document convertion failed." %}";
                    $('#file-view').html('<div id="file-view-tip"><p class="error">' + str + '</p></div>');
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                var str;
                if (xhr.responseText) {
                    str = "{% trans "Document convertion failed." %}";
                } else {
                    str = "{% trans "Failed. Please check the network." %}";
                }
                $('#file-view').html('<div id="file-view-tip"><p class="error">' + str + '</p></div>');
          }
        });
    }

    function check_status () {
        $.ajax({
            url: "{% url 'office_convert_query_status' %}?file_id={{ obj_id }}",
            cache: false,
            dataType: 'json',
            success: function(data) {
                var status = data['status'];
                if (status == 'QUEUED' || status == 'PROCESSING') {
                    setTimeout(check_status, 2000);
                } else {
                    query_page_num();
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                var str;
                if (xhr.responseText) {
                    str = "{% trans "Document convertion failed." %}";
                } else {
                    str = "{% trans "Failed. Please check the network." %}";
                }
                $('#file-view').html('<div id="file-view-tip"><p class="error">' + str + '</p></div>');
          }
      });
  }
  check_status();
  {% endif %}

// </script>
